/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.jsimplemarket.wicket.pages;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.security.core.GrantedAuthority;

import com.googlecode.jsimplemarket.model.ObservatieSpatiuComercial;
import com.googlecode.jsimplemarket.model.Plata;
import com.googlecode.jsimplemarket.model.RaportIncasari;
import com.googlecode.jsimplemarket.service.GenericService;
import com.googlecode.jsimplemarket.service.InchiriereService;
import com.googlecode.jsimplemarket.service.ObservatieSpatiuComercialService;
import com.googlecode.jsimplemarket.service.PlataService;

import java.text.SimpleDateFormat;
import java.text.NumberFormat;


/**
 *
 * @author Alexandru.Codescu
 */
public class AdminPage extends DefaultPageTemplate {
	
	private static final long serialVersionUID = 1L;

    @SpringBean(name = "genericService")
    private GenericService<Plata> servicePlata;
    @SpringBean(name = "plataService")
    private PlataService plataService;
    @SpringBean(name = "inchiriereService")
    private InchiriereService inchiriereService;
    @SpringBean(name = "genericService")
    private GenericService<ObservatieSpatiuComercial> ServiceObservatieSpatiuComercial;    
    @SpringBean(name = "observatieSpatiuComercialService")
    private ObservatieSpatiuComercialService observatieSpatiuComercialService;
    
    private ObservatieSpatiuComercial observatiePiata;
    private Locale locale_ro = new Locale("ro","RO");
	
    private Link createNavigationLink(String id, final Class<? extends WebPage> pageClass, String... roles) {
        Link link = new Link(id) {
            @Override
            public void onClick() {
                setResponsePage(pageClass);
            }
        };
        boolean visible = false;
        for (GrantedAuthority authority: getUtilizator().getAuthorities()) {
            for (String role : roles) {
                if (authority.getAuthority().equalsIgnoreCase(role)) {
                    visible = true;
                    break;
                }
            }
            if (visible) {
                break;
            }
        }
        
        link.setVisible(visible);
        return link;
    }
    
    
    private class PlatiView extends ListView<Object[]> {
    	//Locale locale_ro = new Locale("ro","RO");
        public PlatiView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            
            int index = li.getIndex() + 1;
            li.add(new Label("nrcrt", index));
            li.add(new Label("dayName", (new SimpleDateFormat("EEEE", locale_ro)).format(object[0])));
            li.add(new Label("data", (new SimpleDateFormat("dd.MM.yyyy").format(object[0]))));
            
            NumberFormat fmt = NumberFormat.getCurrencyInstance(locale_ro);
            li.add(new Label("suma", fmt.format(object[1])));
        }
    }
    
    private class PlatiViewByMonth extends ListView<Object[]> {
    	
        public PlatiViewByMonth(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            
            int index = li.getIndex() + 1;
            li.add(new Label("nrcrt", index));
            li.add(new Label("year", (new SimpleDateFormat("Y", locale_ro)).format(object[2])));
            li.add(new Label("month", (new SimpleDateFormat("MMMM", locale_ro).format(object[2]))));
            
            NumberFormat fmt = NumberFormat.getCurrencyInstance(locale_ro);
            li.add(new Label("suma", fmt.format(object[1])));
        }
    }
    
    private String createBonuriByMagazin7Days(int count0, int count15, int count25) {

    	List<RaportIncasari> countList = inchiriereService.queryIncasariByData(new Date());
    	String result = "";
    	result += "Morris.Donut({\n " +
        			"element: 'donut',\n " +
        			"data: [\n "; 
    	int index = 1;
        for (RaportIncasari countlist : countList) {
            //result += "var d = " + countlist.getNrSpatii() + ", ";
            result += "{ label: \"Taxa " + countlist.getValoareTaxa() + " Lei\", value: " + countlist.getNrSpatii() + " }";
            if (index != countList.size()) {
            	result += ",\n";
            }
            index++;
        }
        result += " ]\n ";
        result += "});";
        
        return result;
        
    }
    
    private String LineMorrisValues() {

        List<Object[]> countList = plataService.querySumIncasariByDay();
        String result = "";
        result += "Morris.Line({\n " +
                    "element: 'line',\n " +
                    "data: [\n "; 
        int index = 1;
        for(Object[] obj : countList){
            result += "{ day: '" + obj[0] + "', value: " + obj[1] + " }";
            if (index != countList.size()) {
                result += ",\n";
            }
            index++;
        }
        result += " ],\n ";
        result += " xkey: 'day', ";
        result += " ykeys: ['value'], ";
        result += " labels: ['Value'] ";
        result += "});";
        
        return result;

    }

    private String BarMorrisValues() {
    
        List<Object[]> countList = plataService.querySumIncasariByMonth();
        String result = "";
        result += "Morris.Bar({\n " +
                    "element: 'bar',\n " +
                    "data: [\n "; 
		int index = 1;
		for(Object[] obj : countList){
		     result += "{ y: '" + obj[0] + "', a: " + obj[1] + "}";
		if (index != countList.size()) {
		     result += ",\n";
		     }
		     index++;
		}
//        result += "{y: 'Nov', a: 6500, b: 4780},";
//        result += "{y: 'Dec', a: 7090, b: 5300}";

        result += " ],\n ";
        result += " xkey: 'y', ";
//        result += " ykeys: ['a', 'b'], ";
//        result += " labels: ['R', 'AI'], ";
        result += " ykeys: 'a', ";
        result += " labels: 'Incasari', ";
        result += " hideHover: 'auto', ";
        result += " resize: true ";
        result += "});";

        return result;

    }    
    
    public AdminPage() {

    	final PlatiView platiView = new PlatiView("PlatiByDay", plataService.querySumIncasariByDay());
    	add(platiView);
    	
    	final PlatiViewByMonth platiViewByMonth = new PlatiViewByMonth("PlatiByMonth", plataService.querySumIncasariByMonth());
    	add(platiViewByMonth);

        Label lineValues = new Label("lineValues", LineMorrisValues());
        lineValues.setEscapeModelStrings(false);
        add(lineValues);
        
        Label barValues = new Label("barValues", BarMorrisValues());
        barValues.setEscapeModelStrings(false);
        add(barValues);
        
        Label plot = new Label("plotValues", createBonuriByMagazin7Days(34, 25, 18));
        plot.setEscapeModelStrings(false);
        add(plot);
        
        Link raportIncasari = createNavigationLink("raportIncasariPage", RaportIncasariZilnicePage.class, "ROLE_ADMIN");
        add(raportIncasari);
        
        List<Object[]> countList = plataService.querySumIncasariByDay();
        
        String result = "";
        
        //for (int i = 0; i < countList.size(); i++) {
        for(Object[] obj : countList){
        	//Object[] row = (Object[]) countList.get(i);
        	result += "Element " + obj[1];
        }
        
        String tests = "Lorem ipsum dolor sit amet," +
        		" consectetur adipiscing elit. Vest" +
        		"ibulum tincidunt est vitae ultrice" +
        		"s accumsan. Aliquam ornare lacus a" +
        		"dipiscing, posuere lectus et, frin" +
        		"gilla augue.";
  
    
    	Label labelCount = new Label("labelCount", tests);
        add(labelCount);
        
        final CommentsView commentsView = new CommentsView("lastComments",
        		observatieSpatiuComercialService.queryObservatiiByDay(new Date()) );
        final WebMarkupContainer wmcComments = new WebMarkupContainer("wmcComments");
        wmcComments.setOutputMarkupId(true);
        wmcComments.setOutputMarkupPlaceholderTag(true);
        wmcComments.add(commentsView);

        //add(totalExtraView,extraView, absenteView);
       
        Form<?> form = new Form<Void>("form");
        //form.setModel(new CompoundPropertyModel<ObservatieSpatiuComercial>(observatiePiata));
        
        //final TextField<String> tfDenumire = new TextField<String>("observatie");
        final TextField<String> tfDenumire = new TextField<String>("observatie", new Model<String>(""));
    	//tfValoare.setOutputMarkupId(true);
        
        tfDenumire.setRequired(true);
        tfDenumire.setOutputMarkupId(true);
        tfDenumire.setOutputMarkupPlaceholderTag(true);
        form.add(tfDenumire);
        form.add(wmcComments);
       
        form.add(new AjaxSubmitLink("submit") {

            @Override
            public void onSubmit(AjaxRequestTarget target, Form form) {
                super.onSubmit(target, form);
                tfDenumire.processInput();
                observatiePiata = new ObservatieSpatiuComercial();
                observatiePiata.setUtilizator(getUtilizator());
                observatiePiata.setObservatie(tfDenumire.getValue());
            	ServiceObservatieSpatiuComercial.insert(observatiePiata);
                commentsView.setList(observatieSpatiuComercialService.queryObservatiiByDay(new Date()));
                commentsView.modelChanged();
                target.add(wmcComments);
                tfDenumire.setModel(new Model<String>(""));
                tfDenumire.modelChanged();
                target.add(wmcComments,tfDenumire);
                            
            }
            
        });
        add(form);
       
    }
    
    public String printStandardDate(Date data) {
		return new SimpleDateFormat("dd.MM.yyyy HH:mm").format(data);
	}
    
    private class CommentsView extends ListView<Object[]> {

        public CommentsView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            Label lblUser = new Label("createdBy", object==null ? "0" : object[2].toString());
            Label lblDate = new Label("createdDate", printStandardDate((Date) object[0]));
            Label lblComment = new Label("observatie", object==null ? "0" : object[1].toString());
            li.add(lblUser,lblDate,lblComment);
        }
    }
	
}
